from smb.SMBConnection import SMBConnection

SAMBA_USERNAME = "administrator"
SAMBA_PASSWORD = "vip-859"
SAMBA_PORT = 135 # 445
SAMBA_MYNAME = "DESKTOP-1UR2N71"
SAMBA_REMOTEIP = "192.168.30.177"
SAMBA_DOMAINNAME = "vip-871-1"
SAMBA_DIR = "/down_data/FTP/jss_zl/20181012/2018标准"


class ConnectSamba():

    def __init__(self):
        self.user_name = SAMBA_USERNAME
        self.pass_word = SAMBA_PASSWORD
        # 将标识此连接源自何处的本地NetBIOS计算机名称。您可以自由选择名称，
        # 只要它包含最多15个字母数字字符，并且不包含空格和任何名称\/:*?";|+
        self.my_name = SAMBA_MYNAME
        # 网络域。在Windows上，它被称为工作组。通常，将此参数保留为空字符串是安全的
        self.domain = ''
        # 远程服务器的NetBIOS计算机名称。在Windows上，您可以通过右键单击“我的电脑”
        # 并选择“属性”来查找机器名称。此参数必须与远程服务器上配置的参数相同，否则将拒绝连接。
        self.remote_name = SAMBA_DOMAINNAME
        # 远程ip
        self.remote_smb_IP = SAMBA_REMOTEIP
        # 端口
        self.port = SAMBA_PORT
        self.dir = SAMBA_DIR

        self.conn = None

    def connect_samba(self):
        self.conn = SMBConnection(self.user_name, self.pass_word, self.my_name, self.remote_name, use_ntlm_v2=True)
        print(self.remote_smb_IP)
        print(self.port)
        assert self.conn.connect(self.remote_smb_IP, self.port), BaseException("连接失败")
        return self.conn

    def downloadFile(self, filename, download_filepath):
        '''
        下载文件
        :param filename: 保存到本地的文件名
        :param download_filepath: 保存到本地文件的路径
        :return:c
        '''
        try:
            print("********")
            file_obj = open(download_filepath + filename, 'wb')
            self.conn.retrieveFile(self.dir, filename, file_obj)
            file_obj.close()
            return True
        except:
            return False

    def uploadFile(self, filename, upload_path):
        '''
        上传文件
        :param filename: 上传文件的名称
        :param upload_path: 上传文件的路径
        :return:True or False
        '''
        try:
            conn = SMBConnection(self.user_name, self.pass_word, self.my_name, self.domain_name, use_ntlm_v2=True)
            conn.connect(self.remote_smb_IP, self.port)
            file_obj = open(upload_path + filename, 'rb')
            conn.storeFile(self.dir, filename, file_obj)
            file_obj.close()
            return True
        except:
            return False


conn = ConnectSamba()
conn.connect_samba()
sharelist = conn.conn.listShares()#列出共享目录
for i in sharelist:
    print(i)
